﻿//Manimaran

using System;
using System.Collections.Generic;
using System.IO;


namespace Tzync
{
    public class SafeSync
    {
        private const String SafeSyncFolderPath = GlobalVariables.Drive + GlobalVariables.ProjectName + "\\SafeSync";
        private const String SafeSyncFilePath = SafeSyncFolderPath + "\\safesync";

        private String profileName;
        private List<String> fileList;

        // Constructor called when Program first loads and checks if previous job was safely done
        public SafeSync()
        {
            this.profileName = "";
            SetupFolder();
            fileList = new List<String>();

        }

        public SafeSync(String profileName)
        {
            this.profileName = profileName;
            SetupFolder();
            fileList = new List<String>();
        }

        public String ProfileName
        {
            get { return profileName; }
            set { profileName = value; }
        }

        private void SetupFolder()
        {
            try
            {
                Directory.CreateDirectory(SafeSyncFolderPath);
            }
            catch (DirectoryNotFoundException)
            {
                throw new DirectoryNotFoundException(SafeSyncFolderPath, ActionType.SafeSync);
            }
        }

        /// <summary>
        /// This methods creates the safe sync file
        /// </summary>
        public void Initialize()
        {
            if (File.Exists(SafeSyncFilePath))
            {
                try
                {
                    File.Delete(SafeSyncFilePath);
                }
                catch(DirectoryNotFoundException)
                {
                    throw;
                }
            }
            StreamWriter SW;
            SW = File.CreateText(SafeSyncFilePath);
            SW.WriteLine(profileName);
            SW.Close();
        }

        /// <summary>
        /// Add to the safe sync file once a sync operation is done
        /// </summary>
        /// <param name="action"></param>
        /// <param name="filePath"></param>
        public void Append(SafeSyncType action, String filePath)
        {
            String data = action + "|" + filePath;
            StreamWriter SW;
            SW = File.AppendText(SafeSyncFilePath);
            SW.WriteLine(data);
            SW.Close();
        }

        /// <summary>
        /// Checks if the last sync operation was successful
        /// </summary>
        /// <returns></returns>
        public bool CheckSafelySynced()
        {
            TextReader tr;
            String input = "";
            int counter = 1;

            if (File.Exists(SafeSyncFilePath))
            {
                //Open file
                tr = new StreamReader(SafeSyncFilePath);
                while ((input = tr.ReadLine()) != null)
                {
                    if (input.Trim().Length != 0)
                    {
                        if (counter == 1) profileName = input;
                        else
                        {
                            fileList.Add(input);
                        }
                        counter++;
                    }
                }
                tr.Close();
                if (fileList != null && fileList.Count != 0)
                    if (fileList[fileList.Count - 1].Equals(SafeSyncType.Finished + "|" + SafeSyncType.Finished )) return true;
                    else // last sync was erroneous
                    {
                        return false;
                    }
            }
            return true; // means no syncing problems
        }

        /// <summary>
        /// Does the safe sync to restore the last session
        /// </summary>
        /// <param name="rollBackSystem">Uses the rollback file</param>
        public void PerformSafeSync(RollbackSystem rollBackSystem)
        {
            String[] arrWords;

            foreach (String str in fileList)
            {
                try
                {
                    arrWords = str.Split('|');
                    if (arrWords.Length == 2)
                    {
                        if (arrWords[0].Equals(SafeSyncType.Create.ToString()))
                        {
                            // File was created in the system before synchronization was interrupted
                            // So just delete file in the system
                            if (File.Exists(arrWords[1]))
                            {
                                File.Delete(arrWords[1]);
                            }
                        }
                        else if (arrWords[0].Equals(SafeSyncType.Modify.ToString()))
                        {
                            // File was modified in the system before synchronization was interrupted
                            // So just replace older file taken from rollback folder
                            if (File.Exists(arrWords[1]))
                            {
                                File.Delete(arrWords[1]);
                            }
                            File.Copy(rollBackSystem.GetRollbackFilePath(arrWords[1]), arrWords[1]);

                        }
                        else if (arrWords[0].Equals(SafeSyncType.CreateFolder.ToString()))
                        {
                            // Folder was created in the system before synchronization was interrupted
                            // So just delete folder in the system
                            Directory.Delete(arrWords[1], true);

                        }
                        // No safe sync for deletions in system. 
                        // Becoz it still needs to be deleted after performing safe sync. 
                        // So no point in doing that.
                    }
                }
                catch (FileNotFoundException)
                {
                    continue;
                }
            }
                // Safe sync done. So delete safe sync file
            try
            {
                if (File.Exists(SafeSyncFilePath)) File.Delete(SafeSyncFilePath);
            }
            catch (FileNotFoundException)
            {
                return;
            }
        }
    }
}
